package com.lenovo.smarttraffic.ui.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.Runable.GetDataRunbale;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.EnvironmentBean;
import com.lenovo.smarttraffic.bean.GsonBean.LightValueBean;
import com.lenovo.smarttraffic.ui.adapter.MyRecyclerAdapter;
import com.lenovo.smarttraffic.util.CommonUtil;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.Date;
import java.util.List;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;


/**
 * Created by Caleb.F
 * on 2020-06-29
 * at 14:45
 *
 * @author Caleb.F
 */
public class EnvironmentActivity extends BaseActivity {
    private RecyclerView mMyRecycler;
    private MyRecyclerAdapter myRecyclerAdapter;
    private ProgressDialog mProgressDialog;
    private int lightValueUp = 0;
    private ScheduledFuture<?>  getDataFuture;
    private ScheduledFuture<?>  readDataFuture;
    private static final String TAG = "EnvironmentActivity";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog = new ProgressDialog(this);
        initView();
        getThreshold();
        initData();
    }


    /**
     * 初始化数据
     */
    private void initData() {
        List<EnvironmentBean> all = LitePal.findAll(EnvironmentBean.class);
        if (all.size() != 0) {
            LitePal.deleteAllAsync(EnvironmentBean.class).listen(new UpdateOrDeleteCallback() {
                @Override
                public void onFinish(int rowsAffected) {
                    startThread();
                }
            });
        } else {
            startThread();
        }

    }

    /**
     * 开始请求和读取任务
     */
    private void startThread() {
        //删除完成后开启任务，开始请求网络
        getDataFuture = InitApp.getThreadPoolExecutor().scheduleWithFixedDelay(new GetDataRunbale(),
                0, 3, TimeUnit.SECONDS);
        //开始读取
        Runnable readDataRunable = new Runnable() {
            @Override
            public void run() {
                EnvironmentBean environmentBeans = LitePal.
                        findLast(EnvironmentBean.class);
                Message message = new Message();
                message.what = 1;
                message.obj = environmentBeans;
                handler.sendMessage(message);
            }
        };
       InitApp.getThreadPoolExecutor().
                scheduleWithFixedDelay(readDataRunable, 0, 3, TimeUnit.SECONDS);
    }

    /**
     * 获得光照传感器数值的上限
     */
    private void getThreshold() {
        VolleyUtil.post("GetLightSenseValve.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                LightValueBean lightValueBean = new Gson().fromJson(response, LightValueBean.class);
                lightValueUp = lightValueBean.getUp();
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }


    private void initView() {
        initToolBar("环境指标");
        mMyRecycler = findViewById(R.id.my_recycler);
        initRecycler();
    }


    private void initRecycler() {
        mMyRecycler.setLayoutManager(new GridLayoutManager(this, 3));
        myRecyclerAdapter = new MyRecyclerAdapter(this, new EnvironmentBean(0, 0, 0, 0, 0, 0,
                CommonUtil.getSimpleDateFormat().format(new Date())));
        mMyRecycler.setAdapter(myRecyclerAdapter);
        mMyRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = 80;
                outRect.bottom = 40;
                outRect.left = 100;
            }
        });


    }

    @Override
    protected int getLayout() {
        return R.layout.activity_environment;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    refreshUi(msg);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 刷新UI
     *
     * @param msg
     */
    private void refreshUi(Message msg) {
        EnvironmentBean bean = (EnvironmentBean) msg.obj;
        if (bean == null) {
            mProgressDialog.setTitle("正在读取数据，请稍后");
            mProgressDialog.show();
        } else {
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            //限制數據只有光照有效
            myRecyclerAdapter.setMlist(bean, new EnvironmentBean(
                    40, 20, 300, 1000, lightValueUp, 3));
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(getDataFuture!=null)
        {
            getDataFuture.cancel(true);
        }
        if(readDataFuture!=null){
            readDataFuture.cancel(true);
        }
    }
}
